﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Collections;

namespace ElectronicCommerce.Framework.Data.Entity
{
    /// <summary>
    /// Data source used to fill an entity. The underlying class is IDataReader.
    /// Note: remember to call Dispose() after using.
    /// </summary>
    internal class DataReaderEntitySource : IEntityDataSource, IEnumerable
    {
        private IDataReader dataReader;

        public DataReaderEntitySource(IDataReader dr)
        {
            dataReader = dr;
        }

        public object this[string columnName]
        {
            get { return dataReader[columnName]; }
        }

        public object this[int index]
        {
            get { return dataReader[index]; }
        }

        public IEnumerator<string> GetEnumerator()
        {
            return new ReaderColumnNameEnumerator(dataReader);
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return new ReaderColumnNameEnumerator(dataReader);
        }

        public bool ContainsColumn(string columnName)
        {
            DataTable schemaTable = dataReader.GetSchemaTable();
            foreach (DataRow row in schemaTable.Rows)
            {
                if (string.Compare(row["ColumnName"].ToString().Trim(), columnName.Trim(), true) == 0)
                {
                    return true;
                }
            }
            return false;
        }

        public void Dispose()
        {
            if (dataReader != null)
            {
                dataReader.Close();
                dataReader.Dispose();
            }
        }


        private class ReaderColumnNameEnumerator : IEnumerator<string>
        {
            IEnumerator internalEnumerator;

            public ReaderColumnNameEnumerator(IDataReader dr)
            {
                DataTable schemaTable = dr.GetSchemaTable();
                internalEnumerator = schemaTable.Rows.GetEnumerator();
            }

            public string Current
            {
                get
                {
                    DataRow row = internalEnumerator.Current as DataRow;
                    return row["ColumnName"] as string;
                }
            }

            object System.Collections.IEnumerator.Current
            {
                get { return Current; }
            }

            public bool MoveNext()
            {
                return internalEnumerator.MoveNext();
            }

            public void Dispose()
            {
                return;
            }

            public void Reset()
            {
                internalEnumerator.Reset();
            }
        }
    }
}
